package com.atguigu.distributed.lock.leecode;

/**
 * 力扣中等2182：构造限制重复的字符串
 */
public class RepeatLimitedString {
    static public int N = 26;

    public String repeatLimitedString(String s, int repeatLimit) {
        int[] count = new int[N];
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
        }
        StringBuilder ret = new StringBuilder();
        int m = 0;
        for (int i = N - 1, j = N - 2; i >= 0 && j >= 0; ) {
            if (count[i] == 0) {
                m = 0;
                i--;
            } else if (m < repeatLimit) {
                count[i]--;
                ret.append((char) ('a' + i));
                m++;
            } else if (j >= i || count[j] == 0) {
                j--;
            } else {//当前字符已经超出限制，填入其他字符，并且重置m
                count[j]--;
                ret.append((char) ('a' + j));
                m = 0;
            }
        }
        return ret.toString();
    }
}
